package com.noble.meether.ui.record;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.noble.library.permission.andPermission.Permission;
import com.noble.meether.R;
import com.noble.library.camera.util.FileUtil;
import com.noble.library.log.PToast;
import com.noble.library.permission.PermissionUtil;
import com.noble.library.view.custom.state.CustomFrameLayout;

import java.io.File;

/**
 * 录制视频界面
 */

public class RecordVideoAct extends FragmentActivity implements View.OnClickListener {
    public static final String EXTRA_RECORD_FILE_PATH = "MEET_HER_VIDEO";  // 视频

    private File videoFile;         // 系统的视频文件
    private MediaRecorder mediaRecorder;
    private SurfaceView surfaceView;    // 显示视频预览的SurfaceView
    private Camera camera;          //摄像头

    private boolean isRecording = false;      // 记录是否正在进行录制
    private ImageView ivRecord;
    private TextView tvHintRecord, tvPreview;

    private CustomFrameLayout customLayout;

    private int timeCount = 10;
    private int videoWidth = 1280, videoHeight = 720;
    private int startFailedCnt = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 取消mediaRecorder录制提示音
        ((AudioManager)getSystemService(Context.AUDIO_SERVICE)).setStreamMute(AudioManager.STREAM_SYSTEM,true);
        // 去掉标题栏 ,必须放在setContentView之前
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.act_record_video);
        // 设置横屏显示
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        // 设置全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // 选择支持半透明模式,在有surfaceview的activity中使用。
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        initSurfaceView();

    }

    private void initSurfaceView() {
        // 获取程序界面中的SurfaceView
        surfaceView = findViewById(R.id.sView);
        // 设置分辨率
        surfaceView.getHolder().setFixedSize(1280, 720);
        // 设置该组件让屏幕不会自动关闭
        surfaceView.getHolder().setKeepScreenOn(true);
        SurfaceHolder.Callback callback = new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                doCreate();
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                doChange(holder);
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                doDestory();
            }
        };
        surfaceView.getHolder().addCallback(callback);
        ivRecord = findViewById(R.id.btn_record);
        tvHintRecord = findViewById(R.id.tv_hint_record);
        customLayout = findViewById(R.id.customLayout);
        customLayout.showOfIndex(1);

        tvPreview = findViewById(R.id.tv_preview);
        tvPreview.setOnClickListener(this);
        tvPreview.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_preview:
                String videoPath = videoFile.getAbsolutePath();
                if (TextUtils.isEmpty(videoPath)) {
                    PToast.showShort("无法预览");
                    return;
                }
                VideoPlayDialog playDialog = new VideoPlayDialog(this, videoFile.getAbsolutePath());
                playDialog.show();
                break;
        }
    }

    /**
     * 打开前置摄像头
     */
    private void openFrontCamera() {
        int camIdx = findFrontCamera();
        if (camIdx == -1) {
            PToast.showShort(getResources().getString(R.string.toast_camera_isnull));
            finish();
            return;
        }
        try {
            camera = Camera.open(camIdx);
        } catch (Exception e) {
            PToast.showShort(getResources().getString(R.string.toast_camera_error));
            goToAppSetting();
            finish();
        }
    }

    /**
     * 查找前置摄像头ID
     */
    private int findFrontCamera() {
        int cameraCount;
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        cameraCount = Camera.getNumberOfCameras(); // get cameras number

        for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
            Camera.getCameraInfo(camIdx, cameraInfo); // get camerainfo
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                return camIdx;
            }
        }
        if (cameraCount == 1)
            return Camera.CameraInfo.CAMERA_FACING_BACK;
        return -1;
    }

    private void doChange(SurfaceHolder holder) {
        try {
            camera.setErrorCallback(null);
            camera.setPreviewDisplay(holder);
            camera.cancelAutoFocus();   // 自动聚焦
            //设置surfaceView旋转的角度，系统默认的录制是横向的画面
            camera.setDisplayOrientation(getDegree());
            camera.startPreview();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doCreate() {
//        openFrontCamera();
        try {
            camera = Camera.open();
            mediaRecorder = new MediaRecorder();
        } catch (Exception e) {
            PToast.showShort("打开相机失败，请先进行授权操作");
            finish();
        }
    }

    private void doDestory() {
        stopRecord();
    }

    private int getDegree() {
        //获取当前屏幕旋转的角度
        int rotating = this.getWindowManager().getDefaultDisplay().getRotation();
        int degree = 0;
        //根据手机旋转的角度，来设置surfaceView的显示的角度
        switch (rotating) {
            case Surface.ROTATION_0:
                degree = 90;
                break;
            case Surface.ROTATION_90:
                degree = 0;
                break;
            case Surface.ROTATION_180:
                degree = 270;
                break;
            case Surface.ROTATION_270:
                degree = 180;
                break;
            default:
                break;
        }
        return degree;
    }

    public void record(View v) {
        if (isRecording) {
            resetRecord();
            return;
        }
        PermissionUtil.requestPermission(this, new PermissionUtil.PermissionCallback() {
            @Override
            public void onSuccess() {
                try {
                    if (!Environment.getExternalStorageState().equals(
                            android.os.Environment.MEDIA_MOUNTED)) {
                        PToast.showShort(getResources().getString(R.string.toast_sdcard_isnull));
                        return;
                    }

                    // 创建保存录制视频的视频文件
                    videoFile = FileUtil.getVideoCacheFile();
                    if (startFailedCnt == 0)
                        camera.unlock();
                    mediaRecorder.reset();
                    mediaRecorder.setCamera(camera);
                    // 设置从麦克风采集声音(或来自录像机的声音AudioSource.CAMCORDER)
                    mediaRecorder.setAudioSource(MediaRecorder
                            .AudioSource.MIC);
                    // 设置从摄像头采集图像
                    mediaRecorder.setVideoSource(MediaRecorder
                            .VideoSource.CAMERA);
                    // 设置视频文件的输出格式
                    // 必须在设置声音编码格式、图像编码格式之前设置
                    mediaRecorder.setOutputFormat(MediaRecorder
                            .OutputFormat.MPEG_4);
                    // 设置声音编码的格式
                    mediaRecorder.setAudioEncoder(MediaRecorder
                            .AudioEncoder.AAC);

                    // 设置图像编码的格式
                    mediaRecorder.setVideoEncoder(MediaRecorder
                            .VideoEncoder.H264);

                    mediaRecorder.setVideoSize(videoWidth, videoHeight);
                    mediaRecorder.setVideoEncodingBitRate(1024 * 1024);
                    mediaRecorder.setOrientationHint(getDegree());
                    mediaRecorder.setOutputFile(videoFile.getAbsolutePath());
                    // 指定使用SurfaceView来预览视频
                    mediaRecorder.setPreviewDisplay(surfaceView
                            .getHolder().getSurface());
                    mediaRecorder.setMaxDuration(10000);
                    mediaRecorder.prepare();
                    // 开始录制
                    mediaRecorder.start();
                    isRecording = true;
                    ivRecord.setImageResource(R.drawable.f1_btn_video_recording);
                    tvHintRecord.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
                    cdt.start();
                    tvHintRecord.setText(String.valueOf(timeCount));
                } catch (Exception e) {
                    e.printStackTrace();
                    if (startFailedCnt == 1)
                        return;
                    startFailedCnt++;
                    videoWidth = 640;
                    videoHeight = 480;
                    record(null);
                }
            }

            @Override
            public void onDenied() {
            }
        }, Permission.RECORD_AUDIO, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE);
    }

    public void cancelRecord(View v) {
        if (isRecording)
            return;
        if (mediaRecorder != null) {
            mediaRecorder.release();
        }
        if (camera != null) {
            camera.release();
        }
        finish();
    }

    public void onClickDelete(View v) {
        customLayout.showOfIndex(1);
        tvPreview.setVisibility(View.GONE);
    }

    public void onClickConcat(View v) {
        Intent data = new Intent();
        data.putExtra(EXTRA_RECORD_FILE_PATH, videoFile.getAbsolutePath());
        setResult(RESULT_OK, data);
        finish();
    }

    private final CountDownTimer cdt = new CountDownTimer(11000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            if (tvHintRecord != null)
                tvHintRecord.setText(String.valueOf(millisUntilFinished / 1000));
        }

        @Override
        public void onFinish() {
            timeCount = 10;
            resetRecord();
        }
    };

    private void resetRecord() {
        stopRecord();
        doCreate();
        doChange(surfaceView.getHolder());
    }

    private boolean stopRecord() {
        boolean isOk = false;
        if (isRecording) {
            try {
                tvPreview.setVisibility(View.VISIBLE);
                customLayout.showOfIndex(0);
                Thread.sleep(500);
                tvHintRecord.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                tvHintRecord.setText("您可以录制10秒短视频");
                cdt.cancel();
                mediaRecorder.setOnInfoListener(null);
                mediaRecorder.setOnInfoListener(null);
                mediaRecorder.setPreviewDisplay(null);
                mediaRecorder.stop();
                mediaRecorder.release();
                isOk = true;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                camera.release();
                isRecording = false;
                ivRecord.setImageResource(R.drawable.f1_btn_video_record);
            }
        }
        return isOk;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return isRecording || super.onKeyDown(keyCode, event);
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);

        startActivityForResult(intent, 123);
    }

}
